package org.easydarwin.util;

import android.os.Environment;

import com.eju.cy.drawableview.draw.SerializablePath;

import org.easydarwin.conf.Config;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by stamSuper on 2017/12/26.
 * 功能：
 */

public class PathFileUtil {
    private PathFileUtil(){}
    private static PathFileUtil instance;
    private File file = new File(getSDPath() , "path.txt");
    public static PathFileUtil getInstance(){
        if(null == instance){
            instance = new PathFileUtil();
        }
        return instance;
    }

    public File getFile(){
        return file;
    }

    /**
     * 将折线图集合序列化到本地
     * @param paths
     */
    public void writeListObject(ArrayList<SerializablePath> paths ){
        SerializablePath [] pathArr = new SerializablePath[paths.size()];
        paths.toArray(pathArr);
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file , false ));
            out.writeObject(pathArr);
//            LogUtil.i("===================序列化成功，---- url = " + file.getAbsolutePath());
        } catch (IOException e) {
            LogUtil.i("===================序列化失败 ");
            LogUtil.e(e);
            e.printStackTrace();
        }
    }

    /**
     * 读取序列化的内容
     */
    public ArrayList<SerializablePath> readListObject(){
        File file = new File(getSDPath() , "path.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            SerializablePath[] pathArr = (SerializablePath []) ois.readObject();

            ArrayList<SerializablePath> paths = new ArrayList<>();
            SerializablePath resPath;
            for(int i = 0 ; i< pathArr.length ; i++){
                resPath = new SerializablePath();
                resPath.setColor(pathArr[i].getColor());
                resPath.setWidth(pathArr[i].getWidth());
                float [] point , point0;
                point0 = pathArr[i].getPathPoints().get(0);
                resPath.moveTo(point0[0], point0[1]);
                for(int j = 0 ; j < pathArr[i].getPathPoints().size() ; j++){
                    point =  pathArr[i].getPathPoints().get(j);
                    resPath.lineTo(point[0] , point[1]);
                }
                paths.add(resPath);
            }
            LogUtil.i("===================反序列化成功，---手动转换后-  = " + paths.size());
            return paths;
        } catch (FileNotFoundException e) {
            LogUtil.i("===================反序列化失败 ----- FileNotFoundException");
            LogUtil.e(e);
            e.printStackTrace();
        } catch (IOException e) {
            LogUtil.i("===================反序列化失败 ------ IOException");
            LogUtil.e(e);
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            LogUtil.i("===================反序列化失败----ClassNotFoundException ");
            LogUtil.e(e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将普通文本写入到文本中
     * @param paths
     */
    public void writeJson2File(ArrayList<SerializablePath> paths){
        if(null == paths || paths.size() == 0){
            LogUtil.i("========================================数据为空");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{\"paths\":[");
        for (SerializablePath path : paths){
            sb.append(path.toString()).append(",");
        }
        sb.deleteCharAt(sb.length() -1).append("]}");
        LogUtil.i("========================================发送的数据：" + sb.toString());
        try {
            FileOutputStream fio = new FileOutputStream(file ,false);
            fio.write(sb.toString().getBytes(Config.charset));
            fio.flush();
            fio.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public ArrayList<SerializablePath> getPathsFromJson(String strMsg ){
        return getPathsFromJson(strMsg , 0 , 1, 1);
    }

    /**
     * 读取从服务器获取的path路径（json）
     * @param strMsg   json格式的Path路径
     * @param y        在y轴上的偏移量(default -- 0)
     * @param zoomX     在x轴上的缩放(default -- 1)
     * @param zoomY     在y轴上的缩放(default -- 1)
     * @return
     */
    public ArrayList<SerializablePath> getPathsFromJson(String strMsg , int y , float zoomX ,float zoomY){
        LogUtil.i("=======================PathFileUtil---getPathsFromJson ---height = " + y  +"-----zoomX = " + zoomX + "----zoomY= " + zoomY);
        if(zoomX == 0 || zoomY == 0){
            throw new RuntimeException("zoomx or zoomY can not be 0");
        }
        ArrayList<SerializablePath> resPaths = new ArrayList<>();
        try {
            JSONObject msgObj = new JSONObject(strMsg);
            LogUtil.i("======================读取的数据为：" + strMsg);
            JSONArray paths = msgObj.getJSONArray("paths");
            SerializablePath path ;
            for(int i = 0 ; i< paths.length() ; i++){
                JSONObject pathPoint =  paths.getJSONObject(i);
                path = new SerializablePath();
                path.setColor(pathPoint.getInt("color"));
                path.setWidth(pathPoint.getInt("width"));
                JSONArray pathPoints = pathPoint.getJSONArray("pathPoints");
                JSONArray points , point0;
                float [] point ;
                point0 = pathPoints.getJSONArray(0);
                float tmpX , tmpY;
                path.moveTo((float) (point0.getDouble(0) * zoomX), (float) ((point0.getDouble(1)  + y) * zoomY));
                for(int j = 0 ; j < pathPoints.length() ; j ++){
                    point = new float[2];
                    points = pathPoints.getJSONArray(j);
                    point[0] = (float) points.getDouble(0);
                    point[1] = (float) points.getDouble(1);

                    tmpX = point[0] * zoomX;
                    tmpY = (point[1]  + y) * zoomY;

                    path.lineTo(tmpX , tmpY);
                    path.getPathPoints().add(point);
                }
                resPaths.add(path);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            LogUtil.i("==========================解析json失败：");
            LogUtil.e(e);
        }
//        ArrayList<SerializablePath> serializablePaths = changePath(resPaths);
        return resPaths;
//        binding.paintViewCopy.setPaths(serializablePaths);
    }

    /**
     *读取普通文本，并转换成集合数据
     */
    public ArrayList<SerializablePath> readJsonFromFile(){
        String strMsg = readMsgFromTxt();
        return getPathsFromJson(strMsg);
    }

    /**
     * 将数据转换成能绘制折线图的数据
     * @param pathSource
     * @return
     */
    private ArrayList<SerializablePath> changePath(List<SerializablePath> pathSource){
        ArrayList<SerializablePath> paths = new ArrayList<>();
        SerializablePath resPath;
        for(int i = 0 ; i< pathSource.size() ; i++){
            resPath = new SerializablePath(pathSource.get(i));
            resPath.setColor(pathSource.get(i).getColor());
            resPath.setWidth(pathSource.get(i).getWidth());
            float [] point , point0;
            point0 = pathSource.get(i).getPathPoints().get(0);
            resPath.moveTo(point0[0], point0[1]);
            for(int j = 0 ; j < pathSource.get(i).getPathPoints().size() ; j++){
                point =  pathSource.get(i).getPathPoints().get(j);
                resPath.lineTo(point[0] , point[1]);
            }
            paths.add(resPath);
        }
        return paths;
    }

    /**
     * 获取SD卡根目录
     * @return
     */
    private String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist){
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }


    /**
     * 读取普通写入文本的数据内容
     * @return
     */
    private String readMsgFromTxt() {
        BufferedReader reader;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tmp ;
            while ((tmp = reader.readLine()) != null){
                sb.append(tmp);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
